﻿using KAKA.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Morus;

namespace KAKA.Repository
{
    public class CachingSettingRepository : DecoratedSettingRepository
    {
        private int CacheDurationInMinutes { get; set; }

        public CachingSettingRepository(ISettingRepository innerRepository, int cacheDurationInMinutes)
            : base(innerRepository)
        {
            CacheDurationInMinutes = cacheDurationInMinutes;
        }

        public override Setting GetByName(string name)
        {
            string CacheKey = "setting:{0}".FormatWith(name);

            Setting result;

            Cache.TryGet(CacheKey, out result);

            if (result == null)
            {
                result = base.GetByName(name);

                if ((result != null) && (!Cache.Contains(CacheKey)))
                {
                    Cache.Set(CacheKey, result, DateTime.Now.AddMinutes(CacheDurationInMinutes));
                }
            }

            return result;
        }
    }
}
